package com.hbnu.server.ftf;
import com.hbnu.client.handler.ExceptionHandler;
import com.hbnu.server.ftf.handler.FileServerHandler;
import com.hbnu.server.ftf.handler.GetPathHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import static com.hbnu.tools.PrintTool.println;
import static com.hbnu.tools.ScannerTool.nextLine;

public class FileServer {
    public FileServer() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap.group(boss, worker);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) {
                socketChannel.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                socketChannel.pipeline().addLast(new ObjectEncoder());
                socketChannel.pipeline().addLast(new FileServerHandler());
                socketChannel.pipeline().addLast(new GetPathHandler());
                socketChannel.pipeline().addLast(new ExceptionHandler());
            }
        });
        try {
           serverBootstrap.bind(8972);
            nextLine();
            println("传输关闭");
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
